<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="5" :sm="15">
            <a-form-item label="用户名">
              <a-input placeholder="请输入" v-model="queryParam.userName" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="15">
            <a-form-item label="所属部门">
              <a-tree-select placeholder="请选择" v-model="queryParam.deptId" :treeData="deptTree" :dataList="dataList" :expandedKeys="expandedKeys"> </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="15">
            <a-form-item label="状态">
              <a-select placeholder="请选择" v-model="queryParam.status">
                <a-select-option :value="''">全部</a-select-option>
                <a-select-option :value="'0'">正常</a-select-option>
                <a-select-option :value="'1'">禁用</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="5" d:sm="15">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" icon="search" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button icon="sync" style="margin-left: 8px" @click="handleReset()">重置</a-button>
              <a-button
                v-has="'sys:user:add'"
                style="margin-left: 8px"
                type="primary"
                icon="plus"
                @click="$refs.modal.add()"
                >添加</a-button
              >
              <a-dropdown v-if="'sys:user:remove' && selectedRowKeys.length > 0">
                <a-button type="danger" icon="delete" style="margin-left: 8px" @click="delByIds(selectedRowKeys)"
                  >删除</a-button
                >
              </a-dropdown>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <s-table
      size="default"
      ref="table"
      rowKey="id"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :columns="columns"
      :data="loadData"
      defaultSort="createTime"
    >
      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>
      <span slot="status" slot-scope="text, record">
        <a-switch :checked="record.status == '0'" @change="onChangeStatus(record)" />
      </span>
      <span slot="action" slot-scope="text, record">
        <a v-has="'sys:user:edit'" @click="handleEdit(record)">编辑</a>
        <a-divider type="vertical" />
        <a v-has="'sys:user:remove'" @click="delByIds([record.id])">删除</a>
        <a-divider type="vertical" />
        <a v-has="'sys:user:resetPwd'" @click="resetPwd(record.id)">重置密码</a>
      </span>
    </s-table>
    <user-modal ref="modal" @ok="handleOk" :deptTree="deptTree" />
    <!-- <user-pwd-modal ref="pwdmodal"/> -->
  </a-card>
</template>

<script>
import { STable, SearchTree } from '@/components'
import { getUserList, getDeptListEnable, delUser, changUserStatus, resetPwd } from '@/api/system/sysUser'
import UserModal from './modules/user/UserModal'
import pick from 'lodash.pick'
import { checkPermission } from '@/utils/permissions'
export default {
  name: 'UserList',
  components: {
    SearchTree,
    STable,
    UserModal
  },
  data() {
    return {
      mdl: {},
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'serial' },
        },
        {
          title: '用户名',
          dataIndex: 'userName',
        },
        {
          title: '邮箱',
          dataIndex: 'email',
        },
        {
          title: '手机',
          dataIndex: 'mobile',
        },

        {
          title: '所属部门',
          dataIndex: 'deptName',
        },
        // {
        //   title: '登录时间',
        //   dataIndex: 'loginDate',
        // },
        // {
        //   title: '登录ip',
        //   dataIndex: 'loginIp',
        // },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
        },
        {
          title: '操作',
          width: '200px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        return getUserList(Object.assign(parameter, this.queryParam))
      },
      deptTree: [],
      expandedKeys: [],
      dataList: [],
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  created() {
    getDeptListEnable().then((res) => {
      const data = res.result
      this.buildtree(data, this.deptTree, 0)
      this.expandedKeys = data.map((m) => m.parentId)
      this.dataList = data.map((m) => {
        return { key: m.id, title: m.deptName }
      })
    })
  },
  methods: {
    handleReset() {
      this.queryParam = {
        userName: '',
        status: '',
        deptId: ''
      }
      this.$refs.table.refresh(true)
    },
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    handleAdd(record) {
      this.$refs.modal.add(parentId)
    },
    handleEdit(record) {
      this.$refs.modal.edit(record)
    },
    resetPwd(id) {
      let message = this.$message
      this.$confirm({
        title: '确定重置密码吗?',
        content: '重置后密码为系统默认密码',
        onOk() {
          resetPwd({ id: id }).then((res) => {
            if (res.code === 200) {
              message.success(res.message)
            } else {
              message.error(res.message)
            }
          })
        },
        onCancel() {},
      })
    },
    onChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    delByIds(ids) {
      delUser({ ids: ids.join(',') }).then((res) => {
        if (res.code === 200) {
          this.$message.success(`删除成功`)
          this.handleOk()
        } else {
          this.$message.error(res.msg)
        }
        // const difference = new Set(this.selectedRowKeys.filter(x => !new Set(ids).has(x)))
        // this.selectedRowKeys = Array.from(difference)
        this.selectedRowKeys = []
      })
    },
    onChangeStatus(record) {
      record.status = record.status === '0' ? '1' : '0'
      changUserStatus(pick(record, 'id', 'status')).then((res) => {
        if (res.code === 200) {
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      })
      // 发送状态到服务器
    },
    buildtree(list, arr, parentId) {
      list.forEach((item) => {
        if (item.parentId === parentId) {
          var child = {
            key: item.id,
            value: item.id, // value是给modal的select用的，2者属性不一样
            title: item.deptName,
            scopedSlots: { title: 'title' },
            children: [],
          }
          this.buildtree(list, child.children, item.id)
          if (child.children.length === 0) {
            delete child.children
          }
          arr.push(child)
        }
      })
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  },
}
</script>
